package com.face.common.jsu;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;

import com.face.bean.jsu.MyMap;

public class ReceiveFile {

	FileItemFactory factory = new DiskFileItemFactory();
	private ServletFileUpload upload = new ServletFileUpload(factory);
	private final long MAXSize = 4194304 * 2L;// 4*2MB
	
	public MyMap receiveFile(HttpServletRequest request,String saveDir){
		
		this.upload.setSizeMax(this.MAXSize);
		this.upload.setHeaderEncoding("UTF-8");
		
		MyMap myMap = new MyMap();
		Map<String,String> map = myMap.getMap();
		Map<String, String> fileMap = myMap.getFileMap();
		
		try {
			List<FileItem> items = this.upload.parseRequest(new ServletRequestContext(request));
			if (items != null && !items.isEmpty()) {
				for (FileItem fileItem : items) {
					if (fileItem.isFormField()) {
						String inputName = fileItem.getFieldName();
						String inputValue = new String(fileItem.getString("UTF-8"));
						map.put(inputName, inputValue);
						System.out.println(inputName + ":" + inputValue);
					} else {
						String filename = Rename.rename();
						String filepath = saveDir+ filename;
						System.out.println("文件保存路径为:" + filepath);
						fileMap.put(filename, filepath);
						File file = new File(filepath);
						InputStream inputSteam = fileItem.getInputStream();
						BufferedInputStream fis = new BufferedInputStream(inputSteam);
						FileOutputStream fos = new FileOutputStream(file);
						int f;
						while ((f = fis.read()) != -1) {
							fos.write(f);
						}
						fos.flush();
						fos.close();
						fis.close();
						inputSteam.close();
					}
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
			System.out.println("上传失败");
		} catch (UnsupportedEncodingException e){
			
		} catch (IOException e){
			
		}
		
		return myMap;
		
	}
}
